package com.zzy.demo.common.util.encode;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

public class HexUtil {

	private final static Integer CONVER_LENGTH = 2;

	/**
	 * 将二进制转换成16进制
	 * 
	 * @param buf
	 * @return
	 */
	public static String parseByte2ToByte16Str(byte[] buf) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < buf.length; i++) {
			String hex = Integer.toHexString(buf[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			sb.append(hex.toUpperCase());
		}
		return sb.toString();
	}

	/**
	 * 将16进制转换为二进制
	 * 
	 * @param hexStr
	 * @return
	 */
	public static byte[] parseByte16StrToByte2(String hexStr) {
		if (hexStr.length() < 1) {
			return null;
		}
		byte[] result = new byte[hexStr.length() / CONVER_LENGTH];
		for (int i = 0; i < hexStr.length() / CONVER_LENGTH; i++) {
			int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
			result[i] = (byte) (high * 16 + low);
		}
		return result;
	}
	
	
	public static String encodeHexString(String content) {
		String encodeStr = Hex.encodeHexString(content.getBytes(Charset.forName("UTF-8")));
		return encodeStr;
	}
	
	public static String decodeHexString(String encodeStr) {
		String decodeStr = null;
		try {
			byte[] array = Hex.decodeHex(encodeStr);
			decodeStr = new String(array, Charset.forName("UTF-8"));
			return decodeStr;
		} catch (DecoderException e) {
			e.printStackTrace();
		}
		return decodeStr;
	}	
	
	public static void main(String[] args) throws DecoderException, UnsupportedEncodingException {
		String encodeStr = HexUtil.encodeHexString("zhansgan");
		System.out.println("-----"+encodeStr);
		String hex16 = HexUtil.parseByte2ToByte16Str("zhansgan".getBytes("UTF-8"));
		System.out.println("-----"+hex16);
		byte[] array = HexUtil.parseByte16StrToByte2(hex16);
		System.out.println("-----"+new String(array, Charset.forName("UTF-8")));
		String decodeStr = HexUtil.decodeHexString(encodeStr);
		System.out.println("-----"+decodeStr);
	}

}
